<?php

namespace App\Http\Controllers;

use App\Util\RabbitMqTest;
use PhpAmqpLib\Message\AMQPMessage;

class RabbitTestController extends Controller
{
    protected  $queueName = 'test_queue2';
    protected  $exchangeName = 'test_exchange1';

    //work模式的producer
    public function producer()
    {
        $conn = RabbitMqTest::getInstance()->GetClient();
        $channel = $conn->channel();
        $exchange = $channel->exchange_declare($this->exchangeName,'topic',false,true);
        $channel->queue_declare($this->queueName,false,true,false,false);
        $res = $channel->queue_bind($this->queueName,$this->exchangeName,true);
        $channel->set_ack_handler(
            function (AMQPMessage $message) {
               var_dump("Message acked with content " .  json_encode($message) . PHP_EOL);
            }
        );

        $channel->set_nack_handler(
            function (AMQPMessage $message) {
                var_dump("Message nacked with content " . $message->body . PHP_EOL);
            }
        );
        $channel->confirm_select();
        $data = "hhhhfdddfadfadfaahhh\r\n";
        $msg = new AMQPMessage($data,['delivery_mode' => AMQPMessage::DELIVERY_MODE_PERSISTENT]);
        $channel->basic_publish($msg,$this->exchangeName,'exchange1_queue2');
        echo  ' [x] 已发送 ' , $data, "\n" ;
        var_dump($channel->wait_for_pending_acks(10));
        $channel->close();
        $conn->close();
    }

    public function work1()
    {
        $conn = RabbitMqTest::getInstance()->GetClient();
        $channel = $conn->channel();
        $channel->basic_qos(null,1,null);
        $callBack = function ($msg){
            echo $msg->body;
            $msg->ack();
        };
        $channel->basic_consume($this->queueName,'',false,false,false,false,$callBack);
        while($channel->is_open()) {
           $channel->wait();
         }
        $channel->close();
        $conn->close();
    }

}
